package day2;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Savepoint;

import utility.JdbcUtils;


public class SavePointTest {
	public static void main(String[] args) throws SQLException {
		test();
	}
	
	private static void test() throws SQLException{
		Connection con=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		Savepoint sp=null;
		float money=0;
		
		try {
			con=JdbcUtils.getConnection();
			con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
			con.setAutoCommit(false);
			
			String sql="update user set money=money-100 where id=1";
			ps=con.prepareStatement(sql);
			ps.executeUpdate();
			ps.close();
			sp=con.setSavepoint();
			sql="update user set money=money+100 where id=2";
			ps=con.prepareStatement(sql);
			ps.executeUpdate();
			ps.close();
			
			sql="select money from user where id=2";
			ps=con.prepareStatement(sql);
			rs=ps.executeQuery();
			if(rs.next()){
				money=rs.getFloat(1);
			}
			if(money>400){
				throw new RuntimeException("bigger than max");
			}
			con.commit();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			con.rollback(sp);
			con.commit();
			e.printStackTrace();
		}finally{
			JdbcUtils.free(rs, ps, con);
		}
	}
}
